<template>
  <a-row id="globalHeader" align="center" :wrap="false">
    <a-col flex="auto">
      <a-menu mode="horizontal" :selected-keys="selectedKeys" @menu-item-click="doMenuClick">
        <a-menu-item key="0" :style="{ padding: 0, marginRight: '38px' }" disabled>
          <div class="title-bar">
            <img class="logo" src="../assets/logo.png" />
            <div class="title">{{ title }}</div>
          </div>
        </a-menu-item>
        <a-menu-item v-for="item in visibleRoutes" :key="item.path">
          {{ item.name }}
        </a-menu-item>
      </a-menu>
    </a-col>
    <a-col flex="140px">
      <a-space>
        <a-avatar @click="toLogin">
          <img alt="avatar" :src="store.state?.user.loginUser.avatarUrl" />
        </a-avatar>
        <div>
          <a-dropdown trigger="hover" @select="handleSelect">
            <span>{{ store.state?.user.loginUser?.userName ?? '未登录' }}</span>
            <template #content>
              <a-doption v-for="item in selectOptions" :key="item">{{ item }} </a-doption>
            </template>
          </a-dropdown>
        </div>
      </a-space>
    </a-col>
  </a-row>
</template>

<script setup lang="ts">
import { appRouter, routes } from '@/router/routes'
import { useRouter } from 'vue-router'
import { computed, ref } from 'vue'
import { useStore } from 'vuex'
import checkAccess from '@/access/checkAccess'
import { UserControllerService } from '../../generated'
import message from '@arco-design/web-vue/es/message'

const router = useRouter()
const store = useStore()

// 默认主页
const selectedKeys = ref(['/'])

// TODO 修改title
let title = ref('vueSimple')

// 展示在菜单的路由数组
const visibleRoutes = computed(() => {
  return appRouter.filter((item, index) => {
    if (item.meta?.hideInMenu) {
      return false
    }
    // 根据权限过滤菜单
    if (!checkAccess(store.state.user.loginUser, item?.meta?.access as any)) {
      return false
    }
    return true
  })
})

// 路由跳转后，更新选中的菜单项
router.afterEach((to, from, failure) => {
  selectedKeys.value = [to.path]
})

const doMenuClick = (key: string) => {
  router.push({
    path: key,
  })
}

// 退出账号
const userLogout = async () => {
  try {
    const res = await UserControllerService.userLogoutUsingPost()
    if (res.code === 0) {
      message.success('退出账号成功')
      await router.push({
        path: '/user/login',
      })
    }
  } catch (error) {
    console.error(error)
  }
}

let selectOptions = ['个人信息', '退出账号']

const handleSelect = (v: string) => {
  if (v == '个人信息') {
    return
  }
  if (v == '退出账号') {
    store.commit('userLogout')
    userLogout()
  }
}

const toLogin = () => {
  router.push({
    path: 'user/login',
  })
}
</script>

<style scoped>
.title-bar {
  display: flex;
  align-items: center;
}

.title {
  color: #444;
  margin-left: 16px;
}

.logo {
  height: 48px;
}
</style>
